﻿using Anagramme.Views;
using System;
using System.ApplicationModel;
using System.ApplicationModel.Composition;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Anagramme.Services
{
    /// <summary>
    /// Available application services
    /// </summary>
    public static class ApplicationServices
    {
        private static WeakReference _viewWorkflowManager;
        private static WeakReference _message;
        private static WeakReference _traceSource;
        private static CompositionContainer _container;

        /// <summary>
        /// Get the composition service
        /// </summary>
        public static CompositionContainer Container
        {
            get
            {
                if (object.ReferenceEquals(_container, null))
                {
                    CompositionContainerService compositionService = Application.Current.ApplicationLifetimeObjects.OfType<CompositionContainerService>().Single();
                    _container = compositionService.Container;
                }
                return _container;
            }
        }
        
        /// <summary>
        /// Get the message service
        /// </summary>
        public static IMessageService Message
        {
            get
            {
                if (object.ReferenceEquals(_message, null))
                {
                    _message = new WeakReference(Container.GetExportedValue<IMessageService>());
                }

                return _message.IsAlive ? (IMessageService)_message.Target : null;
            }
        }

        /// <summary>
        /// Get the view workflow service
        /// </summary>
        public static IViewWorkflowManager ViewWorkflow
        {
            get
            {
                if (object.ReferenceEquals(_viewWorkflowManager, null))
                {
                    _viewWorkflowManager = new WeakReference(Container.GetExportedValue<IViewWorkflowManager>());
                }

                return _viewWorkflowManager.IsAlive ? (IViewWorkflowManager)_viewWorkflowManager.Target : null;
            }
        }

        /// <summary>
        /// Get the default trace source
        /// </summary>
        public static TraceSource Trace
        {
            get
            {
                if (object.ReferenceEquals(_traceSource, null))
                {
                    _traceSource = new WeakReference(Application.Current.ApplicationLifetimeObjects.OfType<ITraceService>().Single().Source);
                }

                return _traceSource.IsAlive ? (TraceSource)_traceSource.Target : null;
            }
        }
    }
}
